package d512a.TAKO;

import java.lang.reflect.Array;

import kankan.wheel.widget.OnWheelChangedListener;
import kankan.wheel.widget.WheelView;
import kankan.wheel.widget.adapters.AbstractWheelAdapter;
import kankan.wheel.widget.adapters.ArrayWheelAdapter;
import kankan.wheel.widget.adapters.NumericWheelAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class UserInfoActivity extends Activity {

    private Button saveButton;
    private OnWheelChangedListener dateListener;
    private WheelView weight, height, birthdayYear, birthdayMonth, birthdayDay;
    private RadioGroup rg;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.userinfo);
        
        // Restore settings
        SharedPreferences settings = this.getSharedPreferences("prefs", 0);
        
        String[] months = months();
        
        //Populate wheels 
        weight = populateWheel((WheelView) findViewById(R.id.UserInfoWeight), new NumericWheelAdapter(this, 30, 250), getAdapterIndex(30, Integer.parseInt(settings.getString("weight", "60"))));
        height = populateWheel((WheelView) findViewById(R.id.UserInfoHeight), new NumericWheelAdapter(this, 100, 230), getAdapterIndex(100, Integer.parseInt(settings.getString("height", "170"))));
        birthdayYear = populateWheel((WheelView) findViewById(R.id.UserInfoBirthdayYear), new NumericWheelAdapter(this, 1920, 2011), getAdapterIndex(1920, Integer.parseInt(settings.getString("year", "1980"))));
        birthdayDay = populateWheel((WheelView) findViewById(R.id.UserInfoBirthdayDay), new NumericWheelAdapter(this,  1, 31), getAdapterIndex(1, Integer.parseInt(settings.getString("day", "0"))));
        birthdayMonth = populateWheel((WheelView) findViewById(R.id.UserInfoBirthdayMonth), new ArrayWheelAdapter<String>(this, months), getArrayIndex(months, settings.getString("month", "-1")));
        
        rg = (RadioGroup) findViewById(R.id.Sex);
        rg.check(settings.getInt("sexID", -1));
        
        final Context context = this;
        
        dateListener = new OnWheelChangedListener() {	
        	@Override
			public void onChanged(WheelView wheel, int oldValue, int newValue) {
        		byte currentDay = (byte) birthdayDay.getCurrentItem();
				boolean isLeap = (birthdayYear.getCurrentItem() % 4 == 0);
				switch (birthdayMonth.getCurrentItem()) {
				case 0:
				case 2:
				case 4:
				case 6:
				case 7:
				case 9:
				case 11:
			        birthdayDay.setViewAdapter(new NumericWheelAdapter(context, 1, 31));        
					break;
				case 1:
					
					if (isLeap) {
						birthdayDay.setViewAdapter(new NumericWheelAdapter(context, 1, 29));
					}
					else {
						birthdayDay.setViewAdapter(new NumericWheelAdapter(context, 1, 28));
					}
					if (currentDay >= 29 && isLeap)
						birthdayDay.setCurrentItem(28);
					else if (currentDay >= 28)	
						birthdayDay.setCurrentItem(27);
					break;
				case 3:
				case 5:
				case 8:
				case 10:
			        birthdayDay.setViewAdapter(new NumericWheelAdapter(context, 1, 30));
			        if (currentDay >= 30)
						birthdayDay.setCurrentItem(29);
					break;

				default:
					break;
				}
			}	
		};

		birthdayYear.addChangingListener(dateListener);
		birthdayMonth.addChangingListener(dateListener);
        
		
		saveButton = (Button)this.findViewById(R.id.UserInfoGoalSave);
        saveButton.setOnClickListener(new OnClickListener() { 
            public void onClick(View v) {
                if(rg.getCheckedRadioButtonId() == -1) {
                    Toast.makeText(getApplicationContext(), "Du skal udfylde formen før du kan forsætte",
                            Toast.LENGTH_LONG).show();
                } else {
                    if (saveSettings()) {
                        startActivity(new Intent(getApplicationContext(), HomescreenActivity.class));
                        finish();
                    } else {
                        Toast.makeText(getApplicationContext(), "Der opstod en fejl!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
    }

	private String[] months() {
		return new String[] {"Jan", "Feb", "Mar", "Apr", "Maj", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"};
	}

    // Saves settings
    @SuppressWarnings("unchecked")
    private boolean saveSettings() {
	    SharedPreferences settings = getSharedPreferences("prefs", 0);
        SharedPreferences.Editor editor = settings.edit();
        
	    NumericWheelAdapter nm = (NumericWheelAdapter) weight.getViewAdapter();
	    
	    editor.putString("weight", nm.getItemText(weight.getCurrentItem()).toString());
	    
	    nm = (NumericWheelAdapter) height.getViewAdapter();
        editor.putString("height", nm.getItemText(height.getCurrentItem()).toString());
        
        nm = (NumericWheelAdapter) birthdayYear.getViewAdapter();
        editor.putString("year", nm.getItemText(birthdayYear.getCurrentItem()).toString());
        
        ArrayWheelAdapter<String> awa = (ArrayWheelAdapter<String>) birthdayMonth.getViewAdapter();
        editor.putString("month", awa.getItemText(birthdayMonth.getCurrentItem()).toString());
        
        nm = (NumericWheelAdapter) birthdayDay.getViewAdapter();
        editor.putString("day", nm.getItemText(birthdayDay.getCurrentItem()).toString());
	    
	    RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());
        editor.putString("sex", rb.getText().toString());
        editor.putInt("sexID", rg.getCheckedRadioButtonId());
        
        editor.putBoolean("setSettings", false);
        // Check if settings are saved
        if(editor.commit()){
        	return true;
        }
    	else {
    		Toast.makeText(getApplicationContext(), "Der opstod en fejl" ,
					Toast.LENGTH_LONG).show();
    		return false;
        }	
	}
     
 	protected static WheelView populateWheel(WheelView wheelView, AbstractWheelAdapter adapter, int settings) {
		wheelView.setViewAdapter(adapter);
		wheelView.setVisibility(3);
		wheelView.setCurrentItem(settings);
		return wheelView;
	}
	
	private int getArrayIndex(String[] myArray, String str) {
	    for (int i = 0; i < Array.getLength(myArray); i++) {
	        if (myArray[i] == str) {
	            return(i);
	        }
	    }
	    return(0);
	}
	
	private int getAdapterIndex(int lowValue, int currentValue) {
	    return currentValue - lowValue;
	}
}